import { BASE_URL, BACKEND_URL } from "@/env.js";
// const BASE_URL = '';
console.log("base:", BASE_URL, BACKEND_URL);

import useUserStore from "@/store/user.js";
import { GET_TELD_TOKEN_EXPIRE_TIME } from "./token";
export const initRequest = (vm) => {
  uni.$u.http.setConfig((config) => {
    /* config 为默认全局配置*/
    config.baseURL = BASE_URL; /* 本地根域名 */
    return config;
  });
  // 请求拦截
  uni.$u.http.interceptors.request.use(
    (config) => {
      let token = useUserStore().token;
      const teldToken = useUserStore().teldToken;
      if (token) {
        config.header.Authorization = `Bearer ${token}`;
      }
      // 优化 特来电 相关请求头
      if (config.url?.startsWith("/backend")) {
        const now = new Date().getTime();
        const EXPIRE_TIME = GET_TELD_TOKEN_EXPIRE_TIME();
        // console.log("EXPIRE_TIME:", EXPIRE_TIME);

        if (teldToken && EXPIRE_TIME && now < EXPIRE_TIME) {
          config.baseURL = BACKEND_URL;
          config.url = config.url.replace("/backend/", "/");
          config.header.Authorization = `Bearer ${teldToken}`;
        } else {
          uni.navigateTo({ url: "/pages/token/index" });
          return config;
        }
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
  // 响应拦截
  uni.$u.http.interceptors.response.use(
    (response) => {
      // if (response.data.code == 401) {
      //   // 提示重新登录
      //   uni.$showMsg("请登录");
      //   useUserStore().userLogout();
      //   setTimeout(() => {
      //     uni.switchTab({
      //       url: "/pages/my/my",
      //     });
      //   }, 1000);
      // }

      if (response.data.code === 500) {
        console.log("response:", response);
        if (response.config.url === "/user/info") {
          return response.data.data;
        }

        uni.showToast({
          title: "操作失败",
          icon: "none",
        });
        // return Promise.reject(response);
      }
      // console.log("response.data.data:", response.data.data);

      if (response.data.code === 200) {
        // console.log("response:", response);
        return response.data.data;
      }
      return response;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
};
